<template>
  <div style="width: 100%; height: 100%">
    <div class="maintenance-content-handle">
      <el-button type="primary"
                 @click="openDialog">新增</el-button>
      <!-- <el-button @click="resetSearch">导出</el-button> -->
    </div>
    <el-divider border-style="dashed" />
    <el-table :data="prizesLevelsListData"
              border
              stripe
              style="width: 100%; height: 100%">
      <el-table-column fixed
                       prop="id"
                       label="序号"></el-table-column>
      <el-table-column prop="prizeName"
                       label="奖品名称"></el-table-column>
      <el-table-column prop="prizeLevel"
                       label="奖品等级"></el-table-column>
      <el-table-column prop="dataIndex"
                       label="随机排序">
      </el-table-column>
      <el-table-column prop="修改"
                       label="修改随机排序">

        <template #default="scope">
          <div>只能 未开&&未开 可对换修改</div>

          <div style="display: inline-flex;"
               v-if="scope.row.state == 0">
            <el-input-number v-model="scope.row.changeDataIndex"
                             size="small"
                             :precision="0"
                             :step="1"
                             :max="400" />
            <el-button type="primary"
                       size="small"
                       @click="changeDataItemIndex(scope.row)">修改</el-button>
          </div>
        </template>

      </el-table-column>
      <el-table-column prop="imageUrl"
                       label="奖品图片">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px"
                    :src="scope.row.imageUrl"
                    fit="contain" />
        </template>
      </el-table-column>
      <el-table-column prop="state"
                       label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.state === 0"
                  type="success">未开</el-tag>
          <el-tag v-else
                  type="danger">已开</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary"
                     @click="editItem(scope.row)">编辑</el-button>
          <el-button type="danger"
                     @click="deleteItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="levelsVisible"
             :title="stateVal == 'add' ? '新增奖品等级' : '编辑奖品等级'"
             width="500"
             draggable
             overflow>
    <div class="maintenance-form">
      <el-form :model="formData"
               :rules="rules"
               ref="levelsForm">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="序号"
                          prop="id">
              <el-input v-model="formData.id"
                        :disabled="stateVal == 'add' ? false : true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="奖品名称"
                          prop="prizeName">
              <el-input v-model="formData.prizeName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="奖品等级"
                          prop="prizeLevel">
              <el-input v-model="formData.prizeLevel" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="奖品状态"
                          prop="state">
              <!-- <el-input v-model="formData.state" /> -->
              <el-switch v-model="formData.state"
                         active-text="未开"
                         inactive-text="已开"
                         active-color="#13ce66"
                         inactive-color="#ff4949"
                         :active-value="0"
                         :inactive-value="1">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="奖品图片"
                          prop="imageUrl">
              <el-input v-model="formData.imageUrl" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <!-- 文件上传 -->
            <el-form-item label="维护照片">
              <el-upload action="/mh/cards/uploadFile"
                         :headers="getHeaders()"
                         name="image"
                         accept="image/jpeg, image/png"
                         :limit="1"
                         :before-upload="beforeUpload"
                         :before-remove="beforeRemove"
                         list-type="picture-card"
                         :on-success="handleUploadSuccess">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 提交按钮 -->
        <el-form-item>
          <div style="width: 100%; text-align: center">
            <el-button type="primary"
                       @click="submitForm">{{
              stateVal == 'add' ? '提交' : '编辑'
            }}</el-button>
            <el-button @click="resetForm"
                       v-if="stateVal == 'add'">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script lang='ts' setup>
import {
  ref,
  reactive,
  computed,
  watchEffect,
  watch,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
} from 'vue'

/* 接口 */
import apiHttpFn from '@/api/index'
import { log } from 'console'

interface PrizesLevelsListData {
  id: number | null
  prizeName: string
  prizeLevel: number | null
  imageUrl: string
  dataIndex: number | undefined
  state?: number | undefined
}

// 定义数据

const tokenData = localStorage.getItem('GIS_USER_LOGIN_IDSTR') || ''

// 表单验证规则
const rules = {
  id: [{ required: true, message: '请输入序号', trigger: 'change' }],
  prizeName: [{ required: true, message: '请输入等级名称', trigger: 'change' }],
  prizeLevel: [{ required: true, message: '请输入等级', trigger: 'change' }],
}

// 奖品等级数据
const prizesLevelsListData = ref<PrizesLevelsListData[]>()

// 等级弹窗是否显示
const levelsVisible = ref(false)

// 表单新增
const levelsForm = ref()

// 当前状态
const stateVal = ref('add')

// 表单数据
const formData = ref<PrizesLevelsListData>({
  id: null,
  prizeName: '',
  prizeLevel: null,
  state: undefined,
  dataIndex: undefined,
  imageUrl: '',
})

const emits = defineEmits(['submitFormAdmin'])
const getHeaders = () => {
  const tokenData = localStorage.getItem('GIS_USER_LOGIN_IDSTR') || ''
  return {
    Authorization: tokenData,
  }
}

const beforeRemove = () => {
  formData.value.imageUrl = ''
}

// 修改数据的dataIndex
const changeDataItemIndex = (rowData) => {
  if (rowData?.changeDataIndex <= 0 || rowData?.changeDataIndex >= 400) {
    ElMessage.error('修改的数据超出范围')
    return false
  } else {
    console.log(rowData)
    const currentDataIndex = rowData.dataIndex
    const changeDataIndex = rowData.changeDataIndex
    apiHttpFn
      .changePrizesIndexHttp(tokenData, { currentDataIndex, changeDataIndex })
      .then((res) => {
        console.log(res)
        stateVal.value = 'reset'
        emits('submitFormAdmin', res)
        getLevesData()
      })
  }
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 1
  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 1MB!')
  }
  return (isJPG || isPNG) && isLt2M
}

const handleUploadSuccess = (response, file, fileList) => {
  if (response.message === 'Image uploaded successfully') {
    formData.value.imageUrl = response.imageUrl
  }
}

const openDialog = () => {
  resetForm()
  stateVal.value = 'add'
  levelsVisible.value = true
}

const editItem = (row) => {
  // debugger
  console.log(row)
  stateVal.value = 'edit'
  formData.value = { ...row }
  levelsVisible.value = true
}

const getLevesData = () => {
  apiHttpFn.getPrizesListHttp(tokenData).then((res) => {
    // debugger
    // prizesLevelsListData.value = res.data?.data || []
    let data = res.data.data
    prizesLevelsListData.value = data.filter((item) => {
      item.changeDataIndex = 0
      return item
    })
    console.log(res)
  })
}

const submitForm = () => {
  if (stateVal.value === 'edit') {
    apiHttpFn.updatePrizesHttp(tokenData, formData.value).then((res) => {
      console.log(res)
      getLevesData()
      levelsVisible.value = false
      emits('submitFormAdmin', res)
    })
  } else {
    levelsForm.value.validate((valid) => {
      if (valid) {
        // 提交表单逻辑
        console.log('提交数据:', formData.value)
        apiHttpFn.addPrizesHttp(tokenData, formData.value).then((res) => {
          console.log(res)
          getLevesData()
          levelsVisible.value = false
          emits('submitFormAdmin', res)
        })
      }
    })
  }
}
const resetForm = () => {
  levelsForm.value?.resetFields()
}

const deleteItem = (row) => {
  apiHttpFn.delPrizeslHttp(tokenData, { id: row.id }).then((res) => {
    console.log(res)
    getLevesData()
  })
}

onBeforeMount(() => {
  getLevesData()
})
onMounted(() => {
  console.log('onMounted')
})
onUnmounted(() => {
  console.log('onUnmounted')
})
defineExpose({
  getLevesData,
})
</script>
<style lang='scss' scoped>
</style>
